package com.goods.business.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.mapper.*;
import com.goods.business.service.InStockService;
import com.goods.common.model.business.*;
import com.goods.common.vo.business.InStockDetailVO;
import com.goods.common.vo.business.InStockItemVO;
import com.goods.common.vo.business.InStockVO;
import com.goods.common.vo.business.SupplierVO;
import com.goods.common.vo.system.PageVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class InStockServiceImpl implements InStockService {

    @Autowired
    private InStockMapper inStockMapper;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private InStockInfoMapper inStockInfoMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductStockMapper productStockMapper;

    //入库单（入库记录）数据分页列表展示
    @Override
    public PageVO<InStockVO> findInStockList(Integer pageNum, Integer pageSize, Integer status, Integer type, String inNum, String startTime, String endTime) {
        PageHelper.startPage(pageNum,pageSize);
        Example example = new Example(InStock.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status", status);
        if (null != type) {
            criteria.andEqualTo("type", type);
        }
        if (!StringUtils.isEmpty(inNum)) {
            criteria.andEqualTo("inNum", inNum);
        }
        if (!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date startTime1 = dateFormat.parse(startTime);
                Date endTime1 = dateFormat.parse(endTime);
                criteria.andGreaterThanOrEqualTo("createTime", startTime1)
                        .andLessThanOrEqualTo("createTime", endTime1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<InStock> inStockList = inStockMapper.selectByExample(example);
        List<InStockVO> inStockVOList = inStockList.stream().map(inStock -> {
            InStockVO inStockVO = new InStockVO();
            BeanUtils.copyProperties(inStock, inStockVO);
            Supplier supplier = supplierMapper.selectByPrimaryKey(inStockVO.getSupplierId());
            inStockVO.setSupplierName(supplier.getName());
            return inStockVO;
        }).collect(Collectors.toList());
        PageInfo<InStock> pageInfo = new PageInfo<>(inStockList);
        return new PageVO<>(pageInfo.getTotal(),inStockVOList);
    }

    //查看入库单明细
    @Override
    public InStockDetailVO detailInStock(Long id, Integer pageNum, Integer pageSize) {
        InStockDetailVO inStockDetailVO = new InStockDetailVO();
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        inStockDetailVO.setInNum(inStock.getInNum());
        inStockDetailVO.setStatus(inStock.getStatus());
        inStockDetailVO.setType(inStock.getType());
        inStockDetailVO.setOperator(inStock.getOperator());
        Supplier supplier = supplierMapper.selectByPrimaryKey(inStock.getSupplierId());
        SupplierVO supplierVO = new SupplierVO();
        BeanUtils.copyProperties(supplier,supplierVO);
        inStockDetailVO.setSupplierVO(supplierVO);
        //查询InStockInfo
        InStockInfo stockInfo = new InStockInfo();
        stockInfo.setInNum(inStock.getInNum());
        PageHelper.startPage(pageNum,pageSize);
        List<InStockInfo> inStockInfoList = inStockInfoMapper.select(stockInfo);
        List<InStockItemVO> inStockItemVOList = inStockInfoList.stream().map(inStockInfo -> {
            InStockItemVO inStockItemVO = new InStockItemVO();
            String pNum = inStockInfo.getPNum();
            Product product = new Product();
            product.setPNum(pNum);
            Product product1 = productMapper.selectOne(product);
            inStockItemVO.setId(product1.getId());
            inStockItemVO.setPNum(pNum);
            inStockItemVO.setName(product1.getName());
            inStockItemVO.setModel(product1.getModel());
            inStockItemVO.setUnit(product1.getUnit());
            inStockItemVO.setImageUrl(product1.getImageUrl());
            inStockItemVO.setCount(inStockInfo.getProductNumber());
            return inStockItemVO;
        }).collect(Collectors.toList());
        PageInfo<InStockInfo> pageInfo = new PageInfo(inStockInfoList);
        inStockDetailVO.setTotal(pageInfo.getTotal());
        inStockDetailVO.setItemVOS(inStockItemVOList);
        return inStockDetailVO;
    }

    //将入库单移入回收站
    @Override
    public void removeInStock(Long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        inStock.setModified(new Date());
        inStock.setStatus(1);
        inStockMapper.updateByPrimaryKeySelective(inStock);
    }

    //将回收状态入库单还原
    @Override
    public void backInStock(Long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        inStock.setModified(new Date());
        inStock.setStatus(0);
        inStockMapper.updateByPrimaryKeySelective(inStock);
    }

    //删除入库单
    @Override
    public void deleteStock(Long id) {
        inStockMapper.deleteByPrimaryKey(id);
    }

    //添加入库单
    @Override
    public void addInStock(Map<String, Object> map) {
        Calendar calendar = Calendar.getInstance();
        InStock inStock = new InStock();
        if (!map.containsKey("supplierId")){
            //保存新增来源
            Supplier supplier = new Supplier();
            supplier.setName(map.get("name").toString());
            supplier.setAddress(map.get("address").toString());
            supplier.setEmail(map.get("email").toString());
            supplier.setPhone(map.get("phone").toString());
            supplier.setCreateTime(calendar.getTime());
            supplier.setModifiedTime(calendar.getTime());
            supplier.setSort(Integer.parseInt(map.get("sort").toString()));
            supplier.setContact(map.get("contact").toString());
            supplierMapper.insertSelective(supplier);
            inStock.setSupplierId(supplier.getId());
        } else {
            inStock.setSupplierId(Long.parseLong(map.get("supplierId").toString()));
        }
        //保存入库单
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        inStock.setInNum(uuid);
        inStock.setType(Integer.parseInt(map.get("type").toString()));
        inStock.setOperator("admin");
        inStock.setCreateTime(calendar.getTime());
        inStock.setModified(calendar.getTime());
        List<Map> listMap = (List<Map>) map.get("products");
        Integer productNumber = 0;
        for (Map map1 : listMap) {
            InStockInfo inStockInfo = new InStockInfo();
            Integer number = Integer.parseInt(map1.get("productNumber").toString());
            Long productId = Long.parseLong(map1.get("productId").toString());
            Product product = productMapper.selectByPrimaryKey(productId);
            inStockInfo.setProductNumber(number);
            inStockInfo.setInNum(uuid);
            inStockInfo.setPNum(product.getPNum());
            inStockInfo.setCreateTime(calendar.getTime());
            inStockInfo.setModifiedTime(calendar.getTime());
            inStockInfoMapper.insertSelective(inStockInfo);
            productNumber = productNumber + number;
        }
        inStock.setProductNumber(productNumber);
        inStock.setRemark(map.get("remark").toString());
        inStock.setStatus(2);
        inStockMapper.insertSelective(inStock);
    }

    //入库单审核
    @Override
    public void publishInStock(Long id) {
        InStock inStock = new InStock();
        inStock.setId(id);
        inStock.setModified(new Date());
        inStock.setStatus(0);
        inStockMapper.updateByPrimaryKeySelective(inStock);

    }

    //更新库存数量
    @Override
    public void addProductStock(Long id) {
        InStock inStock = inStockMapper.selectByPrimaryKey(id);
        InStockInfo inStockInfo = new InStockInfo();
        inStockInfo.setInNum(inStock.getInNum());
        List<InStockInfo> inStockInfoList = inStockInfoMapper.select(inStockInfo);
        for (InStockInfo stockInfo : inStockInfoList) {
            ProductStock productStock = new ProductStock();
            productStock.setPNum(stockInfo.getPNum());
            ProductStock productStock1 = productStockMapper.selectOne(productStock);
            if (null != productStock1){
                productStock1.setStock(productStock1.getStock() + stockInfo.getProductNumber());
                productStockMapper.updateByPrimaryKeySelective(productStock1);
            } else {
                productStock.setStock(stockInfo.getProductNumber().longValue());
                productStockMapper.insertSelective(productStock);
            }
        }
    }
}
